import axios from 'axios';
import API_LIST from 'src/API_LIST';
import store from 'src/vuex/store';
import router from 'src/router';

/**
 * 请求发出前处理
 * @param {Object} config
 * @return {*}
 */
function axiosRequestResolve(config) {
	const token = store.getters['userToken/getToken'];
	// @see {@link https://github.com/mzabriskie/axios/issues/209}
	if (token) config.headers.Authorization = `Bearer ${token}`;

	return config;
}
/**
 * 对请求错误处理后件
 */
function axiosRequestReject(error) {
	return Promise.reject(error);
}

/**
 * 清除缓存的数据
 * @return {undefined}
 */
function deleteSession() {
	store.commit('userToken/deleteToken', { root: true });
	store.commit('report/clearUserInfos', { root: true });
	store.commit('menu/clearCache', { root: true });
}

/**
 *  重定向到登陆页面
 */
function redirectToLoginPage() {
	const login_path = sessionStorage.getItem('login_path');
	deleteSession();
	store.commit('userToken/deleteToken');
	router.push({ path: login_path });
}

/**
 * 发现 token 失效则重新请求刷新token
 * @param response
 */
function checkTokenValidateReload(response) {
	if (response.data &&
        parseInt(response.data.code, 10) === API_LIST.TOKEN_ERROR_CODE
	) {
		redirectToLoginPage();
	}
}

/**
 * 对响成功处理
 * @param response
 * @return {*}
 */
function axiosResponseResolve(response) {
	checkTokenValidateReload(response);

	return response;
}

/**
 * 响应错误处理
 * @param error
 * @return {Promise.<*>}
 */
function axiosResponseReject(error) {
	return Promise.reject(error);
}

// 请求拦截器
axios.interceptors.request.use(axiosRequestResolve, axiosRequestReject);

// 响应拦截器
axios.interceptors.response.use(axiosResponseResolve, axiosResponseReject);

export default axios;
